package ch.vd.dec.selt.petale

class TypologieAutorisation {
	
	BaseLegale base
	TypeAutorisation aut
	Categorie cat
	Groupe grp
	Integer priorite = 8
	String uniqueKey = '0#0#0'

	static belongsTo = [base:BaseLegale, aut:TypeAutorisation, cat:Categorie, grp:Groupe]
	
	static mapping = {
		table 'TAUT_TYPO_FAC'
		base column:'BL'
		aut column:'TY_AUT'
		cat column:'CAT'
		grp column:'GRP_SUBCAT'
		priorite column:'PRIORITY'
		uniqueKey column:'UNIQUEKEYSHARP'
		id generator:'sequence', params:[sequence: 'TAUT_TYPO_FAC_SEQ']
		version true
	}
	
	static constraints = {
		base(unique:['aut', 'cat'])
		aut(nullable: true)
		cat(nullable: true)
		grp(nullable: true)
		priorite(blank: false, range:1..8)
		uniqueKey(blank: false, maxSize:30, unique:true)
    }
	
	def definePriorite = {
		priorite = 8  - (base != null ?1:0) - (aut != null ?2:0) - (cat != null ?4:0)
	}

	def defineUniqueKey = {
		uniqueKey = (base != null ?base.id:0) + '#' + (aut != null ?aut.id:0) + '#' + (cat != null ?cat.id:0)
	}
	
	def beforeInsert = {
		definePriorite()
		defineUniqueKey()
	}
	
	def beforeUpdate = {
		definePriorite()
		defineUniqueKey()
	}
}
